package chapter12;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

/**
 * @author : DuJiabao
 * @Date : 2021/2/20 20:57
 * @Project : thinking-in-java
 * @File : null.java
 * @Desc :
 */
public class InputFile {
  private BufferedReader in;

  public InputFile(String name) throws Exception {
    try {
      in = new BufferedReader(new FileReader(name));
    } catch (FileNotFoundException e) {
      // 文件找不到，即没有被打开，因此不需要关闭
      System.out.println("Could not open " + name);
      throw e;
    } catch (Exception e) {
      try {
        in.close();
      } catch (IOException ioException) {
        System.out.println("文件关闭失败");
      }
      throw e;
    } finally {
      // 不要在此关闭文件！
    }
  }

  public String getLine() {
    String s;
    try {
      s = in.readLine();
    } catch (IOException e) {
      throw new RuntimeException("readLine() failed");
    }
    return s;
  }

  public void dispose() {
    try {
      in.close();
      System.out.println("关闭成功");
    } catch (IOException e) {
      throw new RuntimeException("in.close() failed");
    }
  }
}
